package collector.app.nexd.com.singlecollection.presenter.network;


import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import collector.app.nexd.com.singlecollection.R;
import collector.app.nexd.com.singlecollection.application.NexdApplication;
import collector.app.nexd.com.singlecollection.model.User;
import collector.app.nexd.com.singlecollection.util.UrlUtil;

/**
 * Created by xun on 2016/8/8.
 */
public class HttpMethod {


    private RequestQueue requestQueue;
    private static Context mContext;

    private static class SingletonHolder {
        private static final HttpMethod INSTANCE = new HttpMethod();
    }

    public interface OnRequestListener {
        void success(JSONArray data) throws JSONException;

        void requestError(String msg);

        void networkError(String msg);
    }

    //获取单例
    public static HttpMethod getInstance(Context context) {
        mContext = context;
        return SingletonHolder.INSTANCE;
    }

    public HttpMethod() {
        this.requestQueue = NexdApplication.getInstance().getRequestQueue();
    }


    public void execute(String url, final OnRequestListener requestListener, final Map<String, String> params, final String dataField) {
        StringRequest userJson = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject jsonObject = new JSONObject(s);
                    if (!jsonObject.getBoolean("isSuccess")) {
                        requestListener.requestError(ErrorCode.getErrorMsg(mContext, jsonObject.getString("msgCode")));
                    } else {
                        requestListener.success(jsonObject.getJSONArray(dataField));
                    }
                } catch (JSONException e) {
                    requestListener.requestError(mContext.getString(R.string.data_error));
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                requestListener.networkError(volleyError.getMessage());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return params;
            }
        };
        requestQueue.add(userJson);
    }


}
